<template>
    <view class="createCustomer">
        <uni-nav-bar fixed left-icon="left" :title="title" @clickLeft="backHandle" class="unibarS">
            <block slot="right">
                <text class="sub-btn" @click="submit">保存</text>
            </block>
        </uni-nav-bar>
        <!-- 主要内容 -->
        <view class="customer-content">
            <u--form labelPosition="left" :model="params" ref="uForm" labelWidth="70">
                <u-form-item class="item-box" label="回款时间" required @click="openCalendar()"
                    borderBottom ref="item1">
                    <view class="item-temp-box">
                        <view :class="!params.paymentDate ? 'item-temp-text-empty' : ''">{{
                            params.paymentDate || '点击选择' }}</view>
                    </view>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>
                <u-form-item class="item-box" label="回款金额" required borderBottom ref="item1">
                    <u--input v-model="params.paymentAmount" border="none" placeholder="请填写"></u--input>
                </u-form-item>
                <u-form-item class="item-box" label="关联客户" @click="SelectCus()" required borderBottom ref="item1">
                    <view class="item-temp-box">
                        <view :class="!params.customerId ? 'item-temp-text-empty' : ''">{{
                            params.customerName || '点击选择' }}</view>
                    </view>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>
                <u-form-item class="item-box" label="关联订单" @click="SelectOrder()" required borderBottom ref="item1">
                    <view class="item-temp-box">
                        <view v-if="params.relatedOrder.length">{{ params.relatedOrder[0].orderNumber}}</view>
                        <view v-else class="item-temp-text-empty">点击选择</view>
                    </view>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>
                <u-form-item class="item-box" label="付款方式" @click="showSelect('paymentMethod')"
                    borderBottom ref="item1">
                    <view class="item-temp-box">
                        <view :class="!params.paymentMethod ? 'item-temp-text-empty' : ''">
                            {{ bus_pay_status[params.paymentMethod] || '点击选择' }}</view>
                    </view>
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>
                <u-form-item class="item-box" label="备注信息" labelPosition="top" borderBottom ref="item1">
                    <u--textarea v-model="params.remark" border="false" placeholder="请输入备注信息" count
                        style="margin-top: 20rpx; background: #CCCCCC19;"></u--textarea>
                </u-form-item>
				<u-form-item class="item-box" label="附件" labelPosition="top" ref="item1">
					<view class="img_list">
						<view @click="showPhoto" class="upload_box">
							<u-icon name="camera" color="#677585" size="26"></u-icon>
							<view>上传图片</view>
						</view>
						<view class="img_box" v-for="(item, index) in params.paymentScreenshot" :key="index">
							<img @click="previewImg(index)" style="width: 164rpx; height: 164rpx;" :src="item" alt="">
				            <u-icon @click="delImg(index)" class="del_icon" name="close-circle" color="#677585" size="24"></u-icon>
						</view>
					</view>
				</u-form-item>
            </u--form>
        </view>
        <!-- 弹出选择菜单 -->
        <u-action-sheet :show="showActionSheet" :actions="actions" title="请选择" @close="showActionSheet = false"
            @select="sexSelect">
        </u-action-sheet>
        <!-- 选择跟进日期 -->
        <uni-calendar ref="calendar" class="uni-calendar--hook" :clear-date="true" :date="info.date"
            :insert="info.insert" @confirm="confirmCalendar" @close="closeCalendar" />
    </view>
</template>

<script>
import { convertToDict } from '@/common/utils'
import { upImage } from '@/common/utils'
export default {
    data() {
        return {
            title: '新增回款',
            showActionSheet: false,
            params: {
                paymentDate: null,
                paymentAmount: null,
                customerName: null,
                customerId: null,
                relatedOrder: [],
				paymentScreenshot: []
            },

            // 弹出底部弹出菜单，展示的集合
            actions: [],
            count: 4,
            value: 2,
            // 存储属性，用于保存当前正在编辑的表单项
            tempPropName: null,
            showCalendar: false,
            info: {
                insert: false,
                selected: []
            },
            taskTaggingIndex: 1,
            editID: null,
            editType: null
        }
    },
    onLoad(options) {
        this.bus_pay = JSON.parse(uni.getStorageSync('bus_pay_status'))
        this.bus_pay_status = convertToDict(this.bus_pay)

        if(options.id && options.type == 'edit') {
            this.title = '编辑回款'
            this.editID = options.id
            this.editType = true
            this.getDetails()
        }
    },

    methods: {
        getDetails() {
			this.$http.get('/app/payment_received/' + this.editID, {}).then(res => {
				if (res.code == 200) {
                    this.params = res.data
					if(res.data.paymentScreenshot) {
						this.params.paymentScreenshot = res.data.paymentScreenshot.split(',')
					}
                    this.params['relatedOrder'] = [{ orderNumber: res.data.relatedOrder }]
				} else {
					uni.$u.toast(res.msg)
				}
			})
		},
        // 显示选择器
        showSelect(propName) {
            // 客户类型
            if (propName == 'paymentMethod') {
                this.actions = this.bus_pay
            }
            this.tempPropName = propName
            this.showActionSheet = true
        },
        sexSelect(e) {
            this.params[this.tempPropName] = e.dictValue
        },
        // 选择客户
        SelectCus() {
            let that = this
            uni.navigateTo({
                url: '/pages/crm/customer/selectCustomer',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    someEvent: function (data) {
                        that.params.customerId = data.data.id
                        that.params.customerName = data.data.customerName
                    },
                },
                success: function (res) {
					let obj = {
                        id: that.params.customerId,
                        customerName: that.params.customerName
                    }
                    res.eventChannel.emit('emitDataHandle', { data: obj })
                }
            });
        },
        // 选择订单
        SelectOrder() {
            let that = this
            uni.navigateTo({
                url: '/pages/other/selectOrder',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    someEvent: function (data) {
                        let list = JSON.parse(JSON.stringify(data.data))
                        that.params.relatedOrder = list
                    },
                },
                success: function (res) {
					let list = JSON.parse(JSON.stringify(that.params.relatedOrder))
                    res.eventChannel.emit('emitDataHandle', { data: list, customerId: that.params.customerId })
                }
            });
        },

        // 打开日历
        openCalendar() {
            this.$refs.calendar.open()
        },
        // 确定日期
        confirmCalendar(e) {
            console.log(e)
            this.params.paymentDate = e.fulldate
        },
        // 关闭日历
        closeCalendar() { },
        submit() {

            if(!this.params.paymentDate) return uni.$u.toast('请选择回款时间')
            if(!this.params.paymentAmount) return uni.$u.toast('请输入回款金额')
            if(!this.params.customerId) return uni.$u.toast('请选择关联客户')
            if(!this.params.relatedOrder.length) return uni.$u.toast('请填选择订单')

            let obj = JSON.parse(JSON.stringify(this.params))
            delete obj.createTime
            delete obj.updateTime
            delete obj.submissionTime
            obj.relatedOrder = obj.relatedOrder.map(item => item.orderNumber).join(',')
			obj.paymentScreenshot = this.params.paymentScreenshot.join(',')
            if(this.editType) {
                this.$http.put('/app/payment_received', obj).then(res => {
                    let data = res.data
                    if (data.code == 200) {
                        uni.showToast({ title: '成功', duration: 1000 });
                        setTimeout(() => {
                            uni.navigateBack()
                        }, 1000)
                    } 
                })
            } else {
                this.$http.post('/app/payment_received', obj).then(res => {
                    let data = res.data
                    if (data.code == 200) {
                        uni.showToast({ title: '成功', duration: 1000 });
                        setTimeout(() => {
                            uni.navigateBack()
                        }, 1000)
                    } 
                })
            }
        },
        backHandle() {
            uni.navigateBack()
        },
		showPhoto() {
		    let that = this
		    uni.chooseImage({
		        count: 9,
		        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		        sourceType: ['album'], //从相册选择
		        success: function (res) {
		            // console.log(res);
		            // console.log(res.tempFilePaths);
		            upImage(res.tempFilePaths).then(res => {
		                console.log(res)
		                that.params.paymentScreenshot = [...that.params.paymentScreenshot, ...res]
		            })
		        }
		    });
		},
		previewImg(index) {
		    uni.previewImage({
		        current: index,
		        urls: this.params.paymentScreenshot
		    })
		},
		delImg(index) {
		    this.params.paymentScreenshot.splice(index, 1)
		},
    }
}
</script>

<style lang="scss" scoped>
.unibarS {
    /deep/.uni-navbar__header {
        padding: 0 32rpx;
    }

    /deep/.uni-navbar__content {
        border-bottom: none !important;
        box-shadow: 0px 0px 4px rgba(136, 136, 136, 0.12);
    }

    .sub-btn {
        font-size: 32rpx;
        font-weight: 400;
        color: rgba(77, 172, 177, 1);
    }
}

.createCustomer {
    // background: rgba(247, 248, 250, 1);
}

.customer-content {
    margin: 20rpx 0;
}

.item-box {
    border-radius: 16rpx;
    background: rgba(255, 255, 255, 1);
    padding: 0 32rpx;

    /deep/.u-input__content__field-wrapper__field {
        text-align: right !important;
    }

    .rate-box,
    .item-switch {
        width: 100%;
        display: flex;
        justify-content: flex-end;
    }
}

.item-title {
    padding: 48rpx 32rpx 20rpx 32rpx;
    font-size: 32rpx;
    font-weight: 500;
    color: rgba(12, 16, 25, 1);
}

.item-temp-box {
    text-align: right;
    width: 100%;
    font-size: 30rpx;

    >view {
        // 超出隐藏
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}

.item-temp-text-empty {
    font-size: 30rpx;
    font-weight: 400;
    color: rgba(100, 117, 136, 1);
}

.avatar-box {
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .tagging-item {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        margin-left: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;
    }
}

.first-box {
    margin-bottom: 20rpx;
    border-radius: 16rpx;
    background: rgba(255, 255, 255, 1);
    padding: 0 32rpx;
}

.task-item {
    margin-top: 20rpx;
}
.img_list {
	margin-top: 16rpx;
    display: flex;
    flex-wrap: wrap;
    .img_box {
        width: 164rpx;
        height: 164rpx;
        position: relative;
        .del_icon {
            position: absolute;
            top: 0;
            right: 0;
        }
    }
    > view {
        margin-right: 20rpx;
    }
}
.upload_box {
	width: 164rpx;
	height: 164rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	border-radius: 12rpx;
	background: #F7F8FA;
	> view {
		font-size: 24rpx;
		font-weight: 400;
		color: rgba(12, 16, 25, 1);
		margin-top: 8rpx;
	}
}
</style>